#coding:utf8
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
import time
import theano
import theano.tensor as T
import tensorflow as tf
from tensorflow.contrib import rnn
from utils import generateData as generateData
from matplotlib.cbook import flatten
plt.rcParams['font.sans-serif']=['simhei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号

np.random.seed(123)

M,TT,dB,L = 30000, 20000, -10, 1
EqD = int(round((L+10)/2))
SNR = range(-10, 20)

title_size = 18
label_size = 16

# Parameters
learning_rate = 0.001
training_iters = 100000
batch_size = 128
display_step = 10

# Network Parameters
n_input = 13 # MNIST data input (img shape: 28*28)
n_steps = 2 # timesteps
n_hidden = 128 # hidden layer num of features
n_classes = 4 # MNIST total classes (0-9 digits)

# tf Graph input
x = tf.placeholder("float", [None, n_steps, n_input])
y = tf.placeholder("float", [None, n_classes])

# Define weights
weights = {
    'out': tf.Variable(tf.random_normal([n_hidden, n_classes]))
}
biases = {
    'out': tf.Variable(tf.random_normal([n_classes]))
}


def RNN(x, weights, biases):
    # Permuting batch_size and n_steps
    x = tf.transpose(x, [1, 0, 2])
    # Reshaping to (n_steps*batch_size, n_input)
    x = tf.reshape(x, [-1, n_input])
    # Split to get a list of 'n_steps' tensors of shape (batch_size, n_input)
    x = tf.split(x, n_steps, 0)

    # Define a lstm cell with tensorflow
    lstm_cell = rnn.BasicLSTMCell(n_hidden, forget_bias=1.0)

    # Get lstm cell output
    outputs, states = rnn.static_rnn(lstm_cell, x, dtype=tf.float32)

    # Linear activation, using rnn inner loop last output
    return tf.matmul(outputs[-1], weights['out']) + biases['out']

pred = RNN(x, weights, biases)

# Define loss and optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

# Evaluate model
correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

# Initializing the variables
init = tf.global_variables_initializer()

res = []

for db in range(25, 30):
    X, Tx, _ = generateData(30000,20000,db,12, flag='rnn')
    print X.shape, Tx.shape
    with tf.Session() as sess:
        sess.run(init)
        for i in range(100):
            batch_x = X[i*128:(i+1)*128]
            batch_y = Tx[i*128:(i+1)*128]
            batch_x = batch_x.reshape((batch_size, n_steps, n_input))   #128,26,26,
            # print batch_x.shape, batch_y.shape
            sess.run(optimizer, feed_dict={x: batch_x, y: batch_y})

            # Calculate batch accuracy
            acc = sess.run(accuracy, feed_dict={x: batch_x, y: batch_y})
            # Calculate batch loss
            loss = sess.run(cost, feed_dict={x: batch_x, y: batch_y})
            print("Minibatch Loss= " + \
                  "{:.6f}".format(loss) + ", Training Accuracy= " + \
                  "{:.5f}".format(acc))

        test_data = X[0:10*128].reshape((-1, n_steps, n_input))
        test_label = Tx[0:10*128]
        ac = sess.run(accuracy, feed_dict={x: test_data, y: test_label})
        res.append(ac)
        print("db", db," Testing Accuracy:", ac)

print res
